<?php
namespace app;

class db {

	static public $_instance;
	private $dsn;
	private $dbh;

	private function __construct()
	{
		$config = require_once('config/db.php');
		try{
			$this->dsn = 'mysql:host='.$config['host'].';dbname='.$config['dbname'];
			$this->dbh = new \PDO($this->dsn, $config['user'], $config['pwd']);
			$this->dbh->exec('SET NAMES '.$config['charset']);
		}catch(PDOException $e){
			echo $e->getMessage();
		}
	}

	public function __clone()
	{

	}

	public static function getInstance()
	{
		if(self::$_instance === null){
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Query 查询
	 *
	 * @param String $strSql SQL语句
	 * @param String $queryMode 查询方式(All or Row)
	 * @param Boolean $debug
	 * @return Array
	 */
	public function query($strSql, $queryMode = 'All')
	{
		$recordset = $this->dbh->query($strSql);
	    if($recordset){
	    	$recordset->setFetchMode(\PDO::FETCH_ASSOC);
	    	if($queryMode == 'All'){
	        	$result = $recordset->fetchAll();
	    	}elseif($queryMode == 'Row'){
	    		$result = $recordset->fetch();
	    	}
	    }else{
	    	$result = null;
	    }
	    return $result;
	}

	public function insert(Array $rules, Array $values)
	{
		foreach($rules as $k=>$v) {
			$key = "";
			$val = "";
			$count = count($v);
			foreach($v as $k1=>$v1) {
				$key .= $k1 .',';
				$val .= "?,";
			}
			$key = substr($key, 0, -1);
			$val = "(".substr($val, 0, -1)."),";
		}

		$num = count($values);
		$vals = "";
		for ($i=0; $i<$num; $i++) {
			$vals .= $val;
		}

		$vals = substr($vals, 0, -1);

		$sql = "insert into ".$k."(".$key.") values ".$vals;

		$result = self::$dbh->prepare($sql);
		$i = 1;
		foreach($values as $k=>$v) {
			foreach($v as $k1=>$v1) {
				$result->bindValue($i,$v1);
				$i++;
			}
		}
		// echo "---".$i;die;
		return $result->execute();
	}

	public function find($table, $column, $value)
	{
		$sql = "select count(*) from ".$table. " where " .$column." ='".$value."'";
		$result = $this->dbh->query($sql)->fetch();
	    if($result) {
	    	if($result[0] > 0) {
	    		return true;
	    	}
	    } else {
	    	return false;
	    }
	}

	public function inserts($sql)
	{
		return $this->dbh->exec($sql);
	}

	public function update($sql)
	{
		return $this->dbh->exec($sql);
	}

	public function findOne($table, $column, $value)
	{
		$sql = "select * from ".$table. " where " .$column." ='".$value."'";
		$result = $this->dbh->query($sql)->fetch();
	    if($result) {
	    	return $result;
	    } else {
	    	return false;
	    }
	}
}
